/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: LuminosityRulesTestCase.java 283 2010-09-13 08:53:34Z guillaume.sauthier $
 * --------------------------------------------------------------------------
 */


package org.osami.gateway.rules.luminosity;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.conf.ClockTypeOption;
import org.drools.time.SessionPseudoClock;
import org.osami.gateway.profile.gateway.GatewayProfile;
import org.osami.gateway.profile.luminosity.LuminosityProfile;
import org.osami.gateway.rules.luminosity.internal.Activator;
import org.osami.gateway.type.Luminosity;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * A {@code LuminosityRulesTestCase} is ...
 *
 * @author Guillaume Sauthier
 */
public class LuminosityRulesTestCase extends AbstractRulesTestCase {

    private StatefulKnowledgeSession session;

    private MockEventAdmin eventAdmin;
    private SessionPseudoClock clock;

    @BeforeMethod
    private void setUp() throws Exception {
        URL drlUrl = getClass().getResource("LuminosityRuleSet.drl");
        KnowledgeBase base = buildKnowledgeBase(Collections.singleton(drlUrl));

        KnowledgeSessionConfiguration configuration = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
        configuration.setOption(ClockTypeOption.get("pseudo"));

        session = base.newStatefulKnowledgeSession(configuration, null);

        clock = (SessionPseudoClock) session.getSessionClock();

        eventAdmin = new MockEventAdmin();
        session.setGlobal(Activator.EVENT_ADMIN, eventAdmin);

        // Static facts configuration

        GatewayProfile gateway = new GatewayProfile();
        gateway.setIdentifier("B1-163");
        session.insert(gateway);

        LuminosityProfile profile = new LuminosityProfile();
        profile.setBottomValue(100);
        profile.setTopValue(150);
        profile.setPlugId("target-plug-id");
        session.insert(profile);

        Assert.assertNotNull(session);
    }

    @Test
    public void testLuminosityBelowThresholdActivation() throws Exception {

        Luminosity l1 = new Luminosity(10);
        session.insert(l1);

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 1);

        Assert.assertEquals(eventAdmin.postedEvents.size(), 1);
        Event event = eventAdmin.postedEvents.get(0);
        Assert.assertEquals(event.getProperty("source"), "B1-163");
        Assert.assertEquals(event.getProperty("target"), "target-plug-id");
        Assert.assertEquals(event.getProperty("type"), "LUMINOSITY_BELOW_THRESHOLD");
        Assert.assertEquals(event.getProperty("threshold"), 100d);
        Assert.assertEquals(event.getProperty("value"), 10d);

    }

    @Test
    public void testLuminosityBelowThresholdActivationWithMultipleValues() throws Exception {

        Luminosity l1 = new Luminosity(10);
        session.insert(l1);

        Luminosity l2 = new Luminosity(30);
        session.insert(l2);

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 1);

        Assert.assertEquals(eventAdmin.postedEvents.size(), 1);
        Event event = eventAdmin.postedEvents.get(0);
        Assert.assertEquals(event.getProperty("source"), "B1-163");
        Assert.assertEquals(event.getProperty("type"), "LUMINOSITY_BELOW_THRESHOLD");
        Assert.assertEquals(event.getProperty("threshold"), 100d);
        Assert.assertEquals(event.getProperty("value"), 20d);

    }

      
    @Test
    public void testLuminosityAboveThresholdActivation() throws Exception {

        Luminosity l1 = new Luminosity(200);
        session.insert(l1);

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 1);

        Assert.assertEquals(eventAdmin.postedEvents.size(), 1);
        Event event = eventAdmin.postedEvents.get(0);
        Assert.assertEquals(event.getProperty("source"), "B1-163");
        Assert.assertEquals(event.getProperty("target"), "target-plug-id");
        Assert.assertEquals(event.getProperty("type"), "LUMINOSITY_ABOVE_THRESHOLD");
        Assert.assertEquals(event.getProperty("threshold"), 150d);
        Assert.assertEquals(event.getProperty("value"), 200d);

    }

    @Test
    public void testLuminosityAboveThresholdActivationWithMultipleValues() throws Exception {

        Luminosity l1 = new Luminosity(200);
        session.insert(l1);

        Luminosity l2 = new Luminosity(250);
        session.insert(l2);

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 1);

        Assert.assertEquals(eventAdmin.postedEvents.size(), 1);
        Event event = eventAdmin.postedEvents.get(0);
        Assert.assertEquals(event.getProperty("source"), "B1-163");
        Assert.assertEquals(event.getProperty("type"), "LUMINOSITY_ABOVE_THRESHOLD");
        Assert.assertEquals(event.getProperty("threshold"), 150d);
        Assert.assertEquals(event.getProperty("value"), 225d);

    }

    @Test
    public void testLuminosityCloseToBottomThreshold1() throws Exception {

        // Remember
        // * bottom is 100
        // * top is 150

        // Luminosity is gradually going down

        session.insert(new Luminosity(110));
        advanceOf(1000);
        session.insert(new Luminosity(100));
        advanceOf(1000);
        session.insert(new Luminosity(90));
        advanceOf(1000);
        session.insert(new Luminosity(80));
        advanceOf(1000);
        session.insert(new Luminosity(70));

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 1);
        Assert.assertEquals(eventAdmin.postedEvents.size(), 1);
        Event event = eventAdmin.postedEvents.get(0);
        Assert.assertEquals(event.getProperty("type"), "LUMINOSITY_BELOW_THRESHOLD");

    }

    @Test
    public void testLuminosityCloseToBottomThreshold2() throws Exception {

        // Remember
        // * bottom is 100
        // * top is 150

        // Luminosity is close to bottom

        session.insert(new Luminosity(101));
        advanceOf(1000);
        session.insert(new Luminosity(98));
        advanceOf(1000);
        session.insert(new Luminosity(95));
        advanceOf(1000);
        session.insert(new Luminosity(110));
        advanceOf(1000);
        session.insert(new Luminosity(102));

        // Average is above the bottom threshold, so no rules should be fired

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 0);
        Assert.assertEquals(eventAdmin.postedEvents.size(), 0);
    }

    @Test
    public void testLuminosityCloseToBottomThresholdWithIndividualValuesAboveTopThreshold() throws Exception {

        // Remember
        // * bottom is 100
        // * top is 150

        // Luminosity is close to bottom

        session.insert(new Luminosity(101));
        advanceOf(1000);
        session.insert(new Luminosity(98));
        advanceOf(1000);
        session.insert(new Luminosity(167));
        advanceOf(1000);
        session.insert(new Luminosity(184));
        advanceOf(1000);
        session.insert(new Luminosity(102));

        // Average is above the bottom threshold, so no rules should be fired

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 0);
        Assert.assertEquals(eventAdmin.postedEvents.size(), 0);
    }

    private void advanceOf(long units) {
        clock.advanceTime(units, TimeUnit.MILLISECONDS);
    }

    private class MockEventAdmin implements EventAdmin {

        public List<Event> postedEvents = new ArrayList<Event>();
        public List<Event> sendEvents = new ArrayList<Event>();

        public void postEvent(Event event) {
            postedEvents.add(event);
        }

        public void sendEvent(Event event) {
            sendEvents.add(event);
        }
    }
}